//
//  RTVideoMainController.m
//  StoryToy
//
//  Created by baxiang on 2018/1/23.
//  Copyright © 2018年 roobo. All rights reserved.
//

#import "RTVideoMainController.h"
#import "RTVideoSwitch.h"
#import "RTVoiceSwitch.h"
#import "RTRemoteVideoView.h"
#import "RTVideoLandView.h"
#import <ReactiveObjC.h>
#import <RBToyAPI/RBToyAPI.h>
#import <Masonry.h>
#import "AssetsLibrary/AssetsLibrary.h"
#import <Photos/Photos.h>
#include <CommonCrypto/CommonCrypto.h>
#import "RBToyVideoAPI.h"


#define DEVICE_HEIGHT [[UIScreen mainScreen]bounds].size.height
#define DEVICE_WIDTH [[UIScreen mainScreen]bounds].size.width
static NSString * const albumName = @"童秘机器人";

typedef NS_ENUM(NSInteger,RTRemVideoState) {
    RTRemVideoStateConSuc,//连接成功
    RTRemVideoStateConFalse,// 连接失败
    RTRemVideoStateLoginSucc,// 登录成功
    RTRemVideoStateLoginFalse,// 登录失败
    RTRemVideoStateOffline,//设备离线
    RTRemVideoStateCameraOpen, //视频开启
    RTRemVideoStateCameraClose,//视频关闭
};


@interface RTVideoMainController () <RBEAGLVideoViewDelegate, RBLiveObserver>

@property(nonatomic,weak)UIView *voiceBackView;
@property(nonatomic,weak) RBEAGLVideoView *remoteVideoView;
@property(nonatomic,weak) UIView *videoContainView;
@property(nonatomic,weak) UIButton *coutDownBtn;
@property(nonatomic,strong) NSDate *startTime;
@property(nonatomic,strong) RACDisposable *signal;
@property(nonatomic,weak) UIButton *photoBtn;
@property(nonatomic,assign)RTRemVideoState connectState;
@property(nonatomic,weak) UIButton *startVideoBtn;
@property(nonatomic,weak) UIButton *voiceBtn;
@property(nonatomic,weak) RTVoiceSwitch *speakSwitch;
@property(nonatomic,assign)BOOL isFullScreen;
@property(nonatomic,assign)CGRect originFrame;
@property(nonatomic,weak) UIView *mySuperView;
@property(nonatomic,weak) UIView *videoBackView;
@property(nonatomic,weak) UIButton *landFullBtn;
@property(nonatomic,strong) RTVideoLandView *videoLandView;
@property(nonatomic,assign) BOOL isRecording;//是否在录制视频中
@property(nonatomic,assign) BOOL isSpeaking;//是否开启对讲
@property(nonatomic,weak) UIButton *albumBtn;
@property(nonatomic,strong) RBLiveClient* liveClient;
@property(nonatomic,weak) UIImageView *videoDefaultView;
@property(nonatomic,assign) BOOL isReconnect;//是否需要重新连接视频
@property(nonatomic,assign) BOOL isAudioPlay;//是否开启声音
@property(nonatomic,strong) UIView *toastSupView;

@property(nonatomic,copy) NSString *clientId;
@property (nonatomic, assign) BOOL isSettedClient;


@end


@implementation RTVideoMainController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_isFullScreen) {
        [self.navigationController setNavigationBarHidden:YES];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
    }
    UIBarButtonItem *navButton = self.tabBarController.navigationItem.leftBarButtonItem;
    navButton.customView.hidden = YES;
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"视频";
    _toastSupView = self.view;
    self.view.backgroundColor = UIColorHex(0x7290ff);
    
    @weakify(self);
    [RBDeviceApi getDeviceVideoUID:^(RBVideoModel * _Nonnull response, NSError * _Nullable error) {
        @strongify(self);
        if (response) {
            self.clientId = response.videoId;
        }
    }];
    
    [RBLiveClient initGlobal];
    [RBLiveClient setLogLevel:1];
    
    [self setupRemoteView];
    [self setupVoiceView];
    [self setVideoToolView];
    _isAudioPlay = YES;
    [[RACObserve(self, isRecording) distinctUntilChanged] subscribeNext:^(NSNumber *isRecording) {
        if ([isRecording boolValue]) {
            [_videoLandView.fullRecordBtn setSelected:YES];
        }else{
            [_videoLandView.fullRecordBtn setSelected:NO];
        }
    }];
    [RACObserve(self, connectState) subscribeNext:^(NSNumber *connectState) {
        if ([connectState integerValue]==RTRemVideoStateCameraOpen) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [_videoDefaultView setHidden:YES];
            });
            
            if (_isFullScreen) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_videoLandView.fullRecordBtn setEnabled:YES];
                    [_videoLandView.fullPictBtn setEnabled:YES];
                });
            }
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [_videoDefaultView setHidden:NO];
            });
            if (_isFullScreen) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_videoLandView.fullRecordBtn setEnabled:NO];
                    [_videoLandView.fullPictBtn setEnabled:NO];
                });
                
            }
        }
    }];
    [RACObserve(self, isSpeaking) subscribeNext:^(NSNumber *isSpeaking) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.speakSwitch setOn:[isSpeaking boolValue] animated:NO];
            [_videoLandView.speakSwitch setOn:[isSpeaking boolValue] animated:NO];
        });
    }];
    [RACObserve(self, isAudioPlay) subscribeNext:^(NSNumber *isAudioPlay) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [_voiceBtn setSelected:([isAudioPlay boolValue])];
        });
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActiveNotification) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    
//    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//    self.currentStatus = manager.networkReachabilityStatus;
//    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        switch (status) {
//            case AFNetworkReachabilityStatusNotReachable:
//                if (self.currentStatus != status) {
//                    NSLog(@"当前网络已断开");
//                }
//                break;
//            case AFNetworkReachabilityStatusReachableViaWWAN:
//                if (self.currentStatus == AFNetworkReachabilityStatusNotReachable) {
//                    NSLog(@"当前网络已连接");
//                }else if (self.currentStatus != status) {
//                    NSLog(@"当前网络已切换");
//                }
//            case AFNetworkReachabilityStatusReachableViaWiFi:
//                if (self.currentStatus == AFNetworkReachabilityStatusNotReachable) {
//                    NSLog(@"当前网络已连接");
//                }else if (self.currentStatus != status) {
//                    NSLog(@"当前网络已切换");
//                }
//                break;
//            default:
//                break;
//        }
//        self.currentStatus = status;
//    }];
//    [manager startMonitoring];
//
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

-(void)becomeActiveNotification{
    if (_isReconnect) {
        _isReconnect = NO;
        [self startVideoHandle:nil];
    }
}
-(void)enterBackgroundNotification{
    if (_connectState ==RTRemVideoStateCameraOpen) {
        _isReconnect = YES;
        [self startVideoHandle:nil];
    }
}

-(void)setupRemoteView{
    UIView *videoContainView = [UIView new];
    [self.view addSubview:videoContainView];
    videoContainView.backgroundColor = [UIColor clearColor];
    videoContainView.frame = CGRectMake(10,self.navigationController.navigationBar.frame.size.height + 30, DEVICE_WIDTH-20, 450+59);
    videoContainView.layer.cornerRadius = 10;
    videoContainView.layer.masksToBounds = YES;
    _videoContainView = videoContainView;

    
    RTRemoteVideoView *remoteVideoView = [[RTRemoteVideoView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH-20, 200)];
    remoteVideoView.delegate = self;
    [videoContainView addSubview:remoteVideoView];
    _remoteVideoView = remoteVideoView;
    
    UIImageView *videoDefaultView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH-20, 200)];
    [videoContainView addSubview:videoDefaultView];
    videoDefaultView.image = [UIImage imageNamed:@"pic_video"];
    _videoDefaultView = videoDefaultView;
    
    UIButton *coutDownBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoContainView addSubview:coutDownBtn];
    [coutDownBtn setImage:[UIImage imageNamed:@"icon_redpoint"] forState:UIControlStateNormal];
    coutDownBtn.titleLabel.shadowColor = [UIColor blackColor];
    coutDownBtn.titleLabel.shadowOffset = CGSizeMake(0, 0);
    [coutDownBtn setTitle:@"00:01" forState:UIControlStateNormal];
    [coutDownBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    coutDownBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [coutDownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(videoContainView.mas_centerX);
        make.top.mas_equalTo(10);
        make.width.mas_equalTo(200);
    }];
    [coutDownBtn setHidden:YES];
    _coutDownBtn = coutDownBtn;
}

-(void)setupVoiceView{
    UIView *voiceBackView = [UIView new];
    [_videoContainView addSubview:voiceBackView];
    voiceBackView.backgroundColor = UIColorHex(0xf8f8f8);
    [voiceBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(_remoteVideoView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    _voiceBackView = voiceBackView;
    
    UIButton *fullBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_voiceBackView addSubview:fullBtn];
    [fullBtn addTarget:self action:@selector(fullViewsAction) forControlEvents:UIControlEventTouchUpInside];
    [fullBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.width.height.mas_equalTo(33);
        make.centerY.mas_equalTo(_voiceBackView.mas_centerY);
    }];
    [fullBtn setImage:[UIImage imageNamed:@"icon_full_nor"] forState:UIControlStateNormal];
    
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_voiceBackView addSubview:voiceBtn];
    [voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(fullBtn.mas_left).offset(-5);
        make.width.height.mas_equalTo(33);
        make.centerY.mas_equalTo(_voiceBackView.mas_centerY);
    }];
    [voiceBtn addTarget:self action:@selector(voiceHandle:) forControlEvents:UIControlEventTouchUpInside];
    [voiceBtn setImage:[UIImage imageNamed:@"icon_speaker_turnoff_nor"] forState:UIControlStateNormal];
    [voiceBtn setImage:[UIImage imageNamed:@"icon_speaker_turnon_nor"] forState:UIControlStateSelected];
    _voiceBtn = voiceBtn;
    
    RTVoiceSwitch *speakSwitch = [[RTVoiceSwitch alloc] initWithFrame:CGRectMake(10, 5, 80,40)];
    speakSwitch.backgroundColor = [UIColor clearColor];
    [speakSwitch addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];
    [speakSwitch setOn:NO animated:YES];
    _speakSwitch = speakSwitch;
    [_voiceBackView addSubview:speakSwitch];
}

#pragma mark 全屏切换

/**
 全屏设置
 */
-(void)fullViewsAction{
    if(!_isFullScreen){
        self.originFrame = self.videoContainView.frame;
        [UIView animateWithDuration:0.25 animations:^{
            [self.navigationController setNavigationBarHidden:YES];
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:YES];
            self.videoContainView.transform = CGAffineTransformMakeRotation(M_PI/2);
            self.videoContainView.frame = CGRectMake(0, 0 , [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            [self.remoteVideoView setFrame:CGRectMake(0, 0 , [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width)];
            for (UIView *subView  in self.remoteVideoView.subviews) {
                if ([subView isKindOfClass:NSClassFromString(@"GLKView")]) {//视频图层
                    subView.frame = self.remoteVideoView.bounds;
                }
            }
            [self.voiceBackView setHidden:YES];
            [self.videoBackView setHidden:YES];
            self.videoContainView.layer.cornerRadius = 0;
            self.videoContainView.layer.masksToBounds = YES;
            if (!_videoLandView) {
                RTVideoLandView *videoLandView = [RTVideoLandView new];
                _videoLandView = videoLandView;
            }
            _videoLandView.frame = self.remoteVideoView.bounds;
            [self.videoContainView addSubview:_videoLandView];
            
            _videoLandView.videoVC = self;
            @weakify(self);
            _videoLandView.exchangeDefinitionBlock = ^(RTVideoDefini definition) {
                @strongify(self);
                if (definition == RTVideoDefini_640_480) {
                    [self.liveClient setRemoteVideoSize:640 height:480];
                }
                if (definition == RTVideoDefini_1280_720) {
                    [self.liveClient setRemoteVideoSize:1280 height:720];
                }
            };
            [_videoLandView.fullVideoBtn addTarget:self action:@selector(fullViewsAction) forControlEvents:UIControlEventTouchUpInside];
            [_videoLandView.fullBackBtn addTarget:self action:@selector(fullViewsAction) forControlEvents:UIControlEventTouchUpInside];
            [_videoLandView.speakSwitch addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];
            [_videoLandView.fullPictBtn addTarget:self action:@selector(startPhotoHandle:) forControlEvents:UIControlEventTouchUpInside];
            [_videoLandView.fullRecordBtn addTarget:self action:@selector(startRecordHandle:) forControlEvents:UIControlEventTouchUpInside];
//            [_videoLandView.fullAlbumBtn addTarget:self action:@selector(systerAlbumHandle) forControlEvents:UIControlEventTouchUpInside];
            if ( _connectState==RTRemVideoStateCameraOpen) {
                [_videoLandView.videoCntBtn setSelected:YES];
                [_videoLandView.backImageView setHidden:YES];
            }else{
                [_videoLandView.videoCntBtn setSelected:NO];
                [_videoLandView.backImageView setHidden:NO];
            }
            [_videoLandView.fullRecordBtn setSelected:self.isRecording];
            [_videoLandView.speakSwitch setOn:_isSpeaking animated:NO];
            [_videoLandView.videoCntBtn addTarget:self action:@selector(startVideoHandle:) forControlEvents:UIControlEventTouchUpInside];
            [_coutDownBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(75);
            }];
            
        } completion:^(BOOL finished) {
            self.toastSupView = self.videoLandView;
            self.isFullScreen = YES;
        }];
    }else{
        [self.videoLandView hideDefiniView];
        [UIView animateWithDuration:0.25 animations:^{
            [self.navigationController setNavigationBarHidden:NO];
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
            self.videoContainView.transform = CGAffineTransformIdentity;
            self.videoContainView.frame = self.originFrame;
            self.remoteVideoView.frame= CGRectMake(0, 0, DEVICE_WIDTH-20, 200);
            for (UIView *subView  in self.remoteVideoView.subviews) {
                if ([subView isKindOfClass:NSClassFromString(@"GLKView")]) {//视频图层
                    subView.frame = self.remoteVideoView.bounds;
                }
            }
            self.videoContainView.layer.cornerRadius = 10;
            self.videoContainView.layer.masksToBounds = YES;
            [self.voiceBackView setHidden:NO];
            [self.videoBackView setHidden:NO];
            [_videoLandView removeFromSuperview];
            [_coutDownBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(10);
            }];
        } completion:^(BOOL finished) {
            self.toastSupView = self.view;
            self.isFullScreen = NO;
        }];
    }
}

-(void)popViewController {
    [self stopClient];
    _liveClient = nil;
    [self.navigationController setNavigationBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)setAudioLoudspeakerSession{
    AVAudioSession *audioSession=[AVAudioSession sharedInstance];//设置为播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
}

-(void)voiceHandle:(UIButton*)voiceBtn{
    if (self.isAudioPlay) {
        //当前声音开，即将关闭声音
        self.isAudioPlay = NO;
        [_liveClient setEnableAudioPlay:NO];
    }else {
        self.isAudioPlay = YES;
        [self setAudioLoudspeakerSession];
        [_liveClient setEnableAudioPlay:YES];
    }
}

-(void)handleSwitchEvent:(RTVoiceSwitch*)switchView{
    if (_connectState!=RTRemVideoStateCameraOpen) {
        [self showToastView:@"请开启监护"];
        self.isSpeaking = NO;
        return;
    }
    if (switchView.isOn) {
        self.isSpeaking = YES;
        [_liveClient setEnableAudioSend:YES];
    }else{
        self.isSpeaking = NO;
        [_liveClient setEnableAudioSend:NO];
    }
}
-(void)setVideoToolView{
    UIView *videoBackView = [UIView new];
    [_videoContainView addSubview:videoBackView];
    videoBackView.backgroundColor = UIColorHex(0xffffff);
    [videoBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(_voiceBackView.mas_bottom);
        make.height.mas_equalTo(309);
    }];
    _videoBackView = videoBackView;
    
    UIButton *startVideoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoBackView addSubview:startVideoBtn];
    [startVideoBtn setTitle:@"开启监护" forState:UIControlStateNormal];
    [startVideoBtn setTitle:@"关闭监护" forState:UIControlStateSelected];
    startVideoBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [startVideoBtn setTitleColor:UIColorHex(0x4a4a4a) forState:UIControlStateNormal];
    [startVideoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(videoBackView.mas_centerX);
        make.top.mas_equalTo(videoBackView.mas_top).offset(20);
        make.height.width.mas_equalTo(142);
    }];
    _startVideoBtn = startVideoBtn;
    [startVideoBtn addTarget:self action:@selector(startVideoHandle:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *recordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoBackView addSubview:recordBtn];
    [recordBtn setTitle:@"边看边录" forState:UIControlStateNormal];
    recordBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [recordBtn setTitleColor:UIColorHex(0x4a4a4a) forState:UIControlStateNormal];
    [recordBtn addTarget:self action:@selector(startRecordHandle:) forControlEvents:UIControlEventTouchUpInside];
    [recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(startVideoBtn.mas_bottom);
        make.left.mas_equalTo(20);
        make.height.width.mas_equalTo(122);
    }];
    
    UIButton *photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoBackView addSubview:photoBtn];
    [photoBtn setTitle:@"画面截屏" forState:UIControlStateNormal];
    photoBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [photoBtn setTitleColor:UIColorHex(0x4a4a4a) forState:UIControlStateNormal];
    [photoBtn addTarget:self action:@selector(startPhotoHandle:) forControlEvents:UIControlEventTouchUpInside];
    [photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(startVideoBtn.mas_bottom);
        make.right.mas_equalTo(-20);
        make.height.width.mas_equalTo(122);
    }];
    _photoBtn = photoBtn;
    
}


#pragma mark 进入宝宝相册
-(void)systerAlbumHandle{

}

#pragma mark 开启监护
- (void)startVideoHandle:(UIButton*) btn{
    // 先看有没有初始化过client
    if (!_clientId) {
        // 还没有拿到后台给的videoID;
        [SVProgressHUD showErrorWithStatus:@"监护暂不可用，稍后重试"];
        return;
    }
    if (!_isSettedClient) {
        [self initClient];
        _isSettedClient = YES;
    }
    
    if (_connectState!=RTRemVideoStateCameraOpen) {
        [SVProgressHUD show];
        [_liveClient start];
        [_liveClient setVideoRenderer:~(int)0 render:_remoteVideoView];
        if (self.isAudioPlay) {
            [self setAudioLoudspeakerSession];
            [_liveClient setEnableAudioPlay:YES];
        }else {
            NO;
        }
    }else{
        [_liveClient setVideoRenderer:~(int)0 render:nil];
        [_liveClient stop];
        self.connectState = RTRemVideoStateCameraClose;
        [_remoteVideoView clearFrame];
    }
}

#pragma mark 开始录制
-(void)startRecordHandle:(UIButton*)btn{
    if (_connectState!=RTRemVideoStateCameraOpen) {
        [self showToastView:@"请开启监护"];
        return;
    }
    if (!self.isRecording) {
        [_liveClient startRecord:[self recordVideoPath]];
    }else{
        [_liveClient stopRecord];
    }
}
-(NSString*)recordVideoPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *recordfile = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/record.mp4"];
    return recordfile;
}

#pragma mark 截图
-(void)startPhotoHandle:(UIButton*)btn{
    if (_connectState!=RTRemVideoStateCameraOpen) {
        [self showToastView:@"请开启监护"];
        return;
    }
    NSData *imageData = UIImageJPEGRepresentation([_remoteVideoView getLastDrawnFrameImage], 1.0);
    UIImage *currImage = [UIImage imageWithData:imageData];

    [self grantPHAuthorization:^(BOOL granted) {
        if(!granted){
            [SVProgressHUD showErrorWithStatus:@"请在设置界面, 授权访问相册"];
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [self addShotImageAnimailView:currImage];
        });
        [self saveImageOrVideo:currImage isPhotoOrVideo:YES toCollectionWithName:albumName];
    }];
}

- (void)addShotImageAnimailView:(UIImage *)image{
    UIView * view = [[UIView alloc] initWithFrame:self.remoteVideoView.frame];
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
    [_videoContainView addSubview:view];
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:view.bounds];
    imageView.backgroundColor = [UIColor clearColor];
    imageView.layer.borderColor = [UIColor whiteColor].CGColor;
    imageView.layer.borderWidth = 1.5;
    imageView.image = image;
    [view addSubview:imageView];
    [UIView animateWithDuration:0.2 animations:^{
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        imageView.transform = CGAffineTransformScale(CGAffineTransformIdentity, .7, .7);
    }completion:^(BOOL finished) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if([view superview])
                [[view superview] bringSubviewToFront:view];
            [UIView animateWithDuration:0.5 animations:^{
                CGRect rect = [_photoBtn convertRect:_photoBtn.bounds toView:self.remoteVideoView];
                imageView.frame = CGRectInset(rect, 15, 15);
            }completion:^(BOOL finished) {
                [view removeFromSuperview];
            }];
        });
    }];
}

#pragma mark 初始化视频播放器设备
- (void)initClient {
    if (_liveClient == nil) {
        _liveClient = [[RBLiveClient alloc] init];
        [_liveClient setObserver:self];
        [_liveClient setWorkMode:MODE_CLIENT];
        [_liveClient setClientId:_clientId];
        [_liveClient setUserAuth:[NSString stringWithFormat:@"%@",[RBAccessConfig getUserID]] password:[self tokenMd5]];
        
        [_liveClient setEnableAudioSend:NO];
        [_liveClient setEnableAudioPlay:_isAudioPlay];
        [_liveClient setEnableVideoSend:NO];
        [_liveClient setEnableVideoPlay:YES];
    }
}

- (void)stopClient {
    if (_liveClient != nil) {
        [_liveClient setVideoRenderer:~(int)0 render:nil];
        [_liveClient stop];
    }
}

- (NSString *)tokenMd5 {
    // appId + 设备ID(SN) + fromID(userId) + 当前unixtime时间戳前六位
//    RBDevicesDetail *currDetail = [RTDeviceMgr fetchDeviceDetail:RTUserMgr.currDeviceID];
    NSString *appID;
    appID = [NSString stringWithFormat:@"%@",self.deviceModel.appId];
    NSString *deviceID = [NSString stringWithFormat:@"%@", [RBAccessConfig getDeviceID]];
    NSString *fromID = [NSString stringWithFormat:@"%@", [RBAccessConfig getUserID]];

    NSString *dateString = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    NSString *subString = [dateString substringToIndex:6];

    NSString *string = [NSString stringWithFormat:@"%@%@%@%@",appID,deviceID,fromID,subString];
    return [self md5:string];
}

- (NSString *) md5:(NSString *) str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

#pragma mark - RBEAGLVideoViewDelegate

- (void)videoView:(RBEAGLVideoView*)videoView didChangeVideoSize:(CGSize)size {
}

#pragma mark - RVCLiveClientObserver
- (void)OnClientStarted:(int)error {
    NSLog(@"**********开始视频");
}
- (void)OnEvent:(int)type code1:(int)code1 code2:(uint32_t)code2 {
    //NSLog(@"OnEvent %d %d", type, code1);
    [self hideToastView];
    if (type == NET_EVENT) {
        if (code1 == LOGINED) {
            _connectState = RTRemVideoStateLoginSucc;
            NSLog(@"登录成功");
            [self showToastView:@"设备连接成功"];
        } else if (code1 == LOGIN_FAIL) {
            _connectState = RTRemVideoStateLoginFalse;
            NSLog(@"登录失败"); //比如帐号密码错误
            [self showToastView:@"设备连接失败"];
            [_liveClient stop];
        }else if (code1 == LOGIN_TIMEOUT) {
            _connectState = RTRemVideoStateLoginFalse;
            NSLog(@"登录超时");
            [self showToastView:@"设备连接失败"];
            [_liveClient stop];
        }else if (code1 == CONNECTED) {
            _connectState = RTRemVideoStateConSuc;
            NSLog(@"建立连接成功");
        } else if (code1 == DISCONNECTED) {
            NSLog(@"设备断开连接");
            [self showToastView:@"设备连接断开"];
            _connectState = RTRemVideoStateConFalse;
            [_liveClient stop];
        } else if (code1 == DEVICE_OFFLINE) {
            NSLog(@"设备不在线");
            [self showToastView:@"设备不在线"];
            _connectState = RTRemVideoStateOffline;
            [_liveClient stop];
        }
    } else if (type == CLIENT_EVENT) {
        if (code1 == REMOTE_BUSY) {
            NSLog(@"设备忙，开启语音对讲失败");
            [self showToastView:@"设备忙，开启语音对讲失败"];
            self.isSpeaking = NO;
            [_liveClient setEnableAudioSend:false];
        }
    }
}

/**
 视频录制回调
 */
- (void)OnRecorderEvent:(int)msg ext:(int)ext {
    if (msg==2) {//开始视频录制
        self.isRecording = YES;
        _startTime = [NSDate date];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_coutDownBtn setHidden:NO];
        });
        [self countDownHandle];
    }else if (msg == 3){//结束视频录制
        self.isRecording = NO;
        if (!self.signal.isDisposed) [self.signal dispose];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_coutDownBtn setTitle:@"00:01" forState:UIControlStateNormal];
            [_coutDownBtn setHidden:NO];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [_coutDownBtn setHidden:YES];
        });
        [self saveRecoredVideo:nil];
    }
}

- (void)OnClientStoped {
    NSLog(@"视频连接关闭");
    self.connectState = RTRemVideoStateCameraClose;
    [self showToastView:@"视频连接关闭"];
}

- (void)OnVideoCanalOpen:(uint32_t)sid {
    NSLog(@"********视频连接成功"); //开始接收数据
    self.connectState = RTRemVideoStateCameraOpen;
}

- (void)OnVideoCanalClose:(uint32_t)sid {
}

- (void)OnVideoSizeUpdate:(uint32_t)sid width:(int)width height:(int)height {
    if (width==1280&&height==720) {
        dispatch_async(dispatch_get_main_queue(), ^{
            _videoLandView.videoDefini = RTVideoDefini_1280_720;
        });
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            _videoLandView.videoDefini = RTVideoDefini_640_480;
        });
    }
}

-(void)setConnectState:(RTRemVideoState)connectState{
    _connectState = connectState;
    if (_connectState==RTRemVideoStateCameraOpen) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [_startVideoBtn setSelected:YES];
            [_videoLandView.videoCntBtn setSelected:YES];
            [_videoLandView.backImageView setHidden:YES];
        });
        
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [_startVideoBtn setSelected:NO];
            [_videoLandView.videoCntBtn setSelected:NO];
            [_videoLandView.backImageView setHidden:NO];
        });
    }
}

#pragma mark UI改变在主线程

-(void)showToastView:(NSString*)content{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showErrorWithStatus:content];
    });
}

- (void)hideToastView {
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
}

-(void)countDownHandle{
    RACSignal *racSignal = [RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]];
    _signal = [racSignal subscribeNext:^(NSDate * _Nullable x) {
        NSInteger result = [x timeIntervalSinceDate:_startTime];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *timeStr = [NSString stringWithFormat:@"%02ld:%02ld",result/60%60,result%60];
            [_coutDownBtn setTitle:timeStr forState:UIControlStateNormal];
        });
    }];
}

- (void)saveRecoredVideo:(void(^)(NSString * tipString)) block{
    NSString * path = [self recordVideoPath];
    BOOL isEsit = [[NSFileManager defaultManager] fileExistsAtPath:path];
    if(!isEsit){
        return;
    }
    
    [self grantPHAuthorization:^(BOOL granted) {
        if(!granted){
            [SVProgressHUD showErrorWithStatus:@"请在设置界面, 授权访问相册"];
            return;
        }
        
        [self saveImageOrVideo:[NSURL fileURLWithPath:path] isPhotoOrVideo:NO toCollectionWithName:albumName];
    }];

}

#pragma mark 外界调用获取是否正在直播

- (BOOL)isLiving {
    if (self.connectState == RTRemVideoStateCameraOpen) {
        return YES;
    }
    return NO;
}

#pragma mark PHPhotoLibrary

/**
 获取相册的权限

 @param block 获取相册权限的block，granted true 获取到, false others
 */
-(void) grantPHAuthorization:(void(^)(BOOL granted))block
{
    // 1. 获取当前App的相册授权状态
    PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];

    // 2. 判断授权状态
    if (authorizationStatus == PHAuthorizationStatusAuthorized) {

        // 2.1 如果已经授权, 保存图片(调用步骤2的方法)
        if(block)
            block(YES);

    } else if (authorizationStatus == PHAuthorizationStatusNotDetermined) { // 如果没决定, 弹出指示框, 让用户选择

        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

            // 如果用户选择授权, 则保存图片
            if (status == PHAuthorizationStatusAuthorized) {
                if(block)
                    block(YES);
            }else{
                if(block)
                    block(NO);
            }
        }];

    } else {
        if(block)
            block(NO);
    }
}

/**
 保存图片或者视频

 @param imageOrVideo 图片或视频,图片是UIImage或者NSURL类，视频是NSURL
 @param isPhoto 是不是图片
 @param collectionName 相册名字
 */
- (void)saveImageOrVideo:(id)imageOrVideo isPhotoOrVideo:(BOOL)isPhoto toCollectionWithName:(NSString *)collectionName {

    NSLog(@"存储到相册");
}

@end
